//
//  PMSPopupView.swift
//  TuJiaMerchant
//
//  Created by 王文辉 on 14-9-24.
//  Copyright (c) 2014年 途家. All rights reserved.
//

import UIKit

open class PMSPopupView: TPKeyboardAvoidingScrollView
{
     /// 此宽度和原生弹层一致
    
    let bottomHeight : CGFloat = 48
    //
    public var cancelAction: (()->Void)?
    public var callBackT:(()->Void)?
    public var contentView:UIView?
    public var isAnimation: Bool = false
    public var controller : UIViewController?
    // keep btmView leftBtn rightBtn for display control
    fileprivate var showBottom = true
    
    //
    @discardableResult
    public class func showAlert(_ title: String, cancelItem: String, otherItem: String? = nil, callback:(()->Void)? = nil) -> PMSPopupView {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: TuJiaAutoLayoutPopupView.contentFixedWidth, height: 110.0))
        label.text = title as String
        label.numberOfLines = 0
        label.textAlignment = .center
        label.font = VS.font16
        
        let popview: PMSPopupView = PMSPopupView(view: label, leftItem: cancelItem, rightItem: otherItem, rightAction: callback)
        popview.show()
        return popview
    }
    
    public class func showAlertWithContentAlignLeft(_ title: String, cancelItem: String, viewHight: CGFloat, otherItem: String? = nil, callback:(()->Void)? = nil) -> PMSPopupView {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: TuJiaAutoLayoutPopupView.contentFixedWidth, height: viewHight))
        let label = UILabel(frame: CGRect(x: 20.0, y: 20, width: view.w - 40.0, height: viewHight - 28.0))
        label.text = title as String
        label.numberOfLines = 0
        label.textAlignment = .left
        label.font = VS.font14
        view.addSubview(label)
        
        let popview: PMSPopupView = PMSPopupView(view: view, leftItem: cancelItem, rightItem: otherItem, rightAction: callback)
        popview.show()
        return popview
    }
    
    //
    override public init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    //
    public init(view: UIView, leftItem: String, rightItem: String? = nil, rightAction:(()->Void)? = nil) {
        
        //
        super.init(frame: CGRect.zero)
        
        let w = CommonDefine.kScreenWidth
        
        // 两边留间隙
        let adjustWidth = w - TuJiaAutoLayoutPopupView.contentFixedWidth
        contentView = UIView(frame: CGRect(x: adjustWidth / 2, y: CommonDefine.kScreenFullHeight, width: TuJiaAutoLayoutPopupView.contentFixedWidth, height: view.frame.size.height+bottomHeight))
        contentView!.backgroundColor = UIColor.white
        contentView!.layer.cornerRadius = 10.0
        contentView!.clipsToBounds = true
        contentView!.autoresizesSubviews = true
//        contentView!.setTranslatesAutoresizingMaskIntoConstraints(true)

        
        //
        contentView!.addSubview(view)
        self.addSubview(contentView!)
        
        //
        let btmSep = UIView(frame: CGRect(x: 0.0, y: view.frame.size.height-CommonDefine.kPixel, width: w, height: CommonDefine.kPixel))
        btmSep.backgroundColor = VS.sepControlGray
        btmSep.autoresizingMask = UIView.AutoresizingMask.flexibleTopMargin
        contentView!.addSubview(btmSep)
        let btmView = UIView(frame: CGRect(x: 0.0, y: view.frame.size.height, width: w, height: self.bottomHeight))
        btmView.backgroundColor = UIColor.white
        btmView.autoresizingMask = UIView.AutoresizingMask.flexibleTopMargin
        contentView!.addSubview(btmView)
        
        //
//        let leftBtn: UIButton = UIButton(frame: CGRectMake((rightItem == nil ? w/2.0-70.0:20.0), view.frame.size.height+20.0, 120.0, 32.0))
        //let orignX = (contentView!.frame.size.width/2.0 - 120) / 2.0
        let leftBtn = UIButton(frame: CGRect(x: 0, y: view.h, width: rightItem == nil ? contentView!.w : contentView!.w/2, height: self.bottomHeight))
//        let image = UIImage(named: "cancel.png")!.resizableImageWithCapInsets(UIEdgeInsets(top: 0.0, left: 15.0, bottom: -0.5, right: 15.0))
//        leftBtn.setBackgroundImage(image, forState: UIControlState.Normal)
        leftBtn.setTitle(leftItem as String, for: UIControl.State())
        leftBtn.setTitleColor(rightItem == nil ? VS.mainBlue : VS.txtMain, for: UIControl.State())
        leftBtn.titleLabel?.font = VS.font16
        leftBtn.addTarget(self, action: #selector(PMSPopupView.cancel), for: UIControl.Event.touchUpInside)
        //leftBtn.setTranslatesAutoresizingMaskIntoConstraints(false)
        leftBtn.autoresizingMask = UIView.AutoresizingMask.flexibleTopMargin;
        leftBtn.setBackgroundColor(VS.sepPageGray, forState: .highlighted)
        contentView!.addSubview(leftBtn)
        //contentView!.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[leftBtn]-20-|", options: NSLayoutFormatOptions.AlignAllBottom, metrics: nil, views: ["leftBtn": leftBtn]))
        //contentView!.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("leftBtn(120@32)", options: NSLayoutFormatOptions.AlignAllBottom, metrics: nil, views: ["leftBtn": leftBtn]))
        //contentView!.addConstraint(NSLayoutConstraint(item: leftBtn, attribute:NSLayoutAttribute.BottomMargin, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -20.0))
        
        //
        if let rightItemInIf = rightItem {
//            let rightBtn: UIButton = UIButton(frame: CGRectMake(w-160.0, view.frame.size.height+20.0, 120.0, 32.0))
            //let rightOriginX = contentView!.frame.size.width/2.0 + orignX
            let rightBtn = UIButton(frame: CGRect(x: leftBtn.r, y: view.h, width: contentView!.w/2, height: self.b))
//            let image = UIImage(named: "confirm.png")!.resizableImageWithCapInsets(UIEdgeInsets(top: 0.0, left: 15.0, bottom: -0.5, right: 15.0))
//            rightBtn.setBackgroundImage(image, forState: UIControlState.Normal)
            rightBtn.setTitle(rightItemInIf as String, for: UIControl.State())
            rightBtn.setTitleColor(VS.mainBlue, for: UIControl.State())
            rightBtn.titleLabel?.font = VS.font16
            rightBtn.addTarget(self, action: #selector(PMSPopupView.confirm), for: UIControl.Event.touchUpInside)
            rightBtn.autoresizingMask = UIView.AutoresizingMask.flexibleTopMargin;
            rightBtn.setBackgroundColor(VS.sepPageGray, forState: .highlighted)
            contentView!.addSubview(rightBtn)
            
            //contentView!.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[rightBtn]-20-|", options: NSLayoutFormatOptions.AlignAllBottom, metrics: nil, views: ["rightBtn": rightBtn]))
            let sepHeightRate : CGFloat = 0.4
            let btnSep = UIView(frame: CGRect(x: contentView!.w/2,y: leftBtn.y + bottomHeight * (1-sepHeightRate)/2, width: CommonDefine.kPixel, height: bottomHeight * sepHeightRate))
            btnSep.setBorder(color: VS.sepPageGray)
            btnSep.autoresizingMask = UIView.AutoresizingMask.flexibleTopMargin
            contentView?.addSubview(btnSep)
            
            callBackT = rightAction
        }
        
        //
        self.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
        self.frame = CGRect(x: 0.0, y: 0.0, width: w, height: contentView!.frame.origin.y)
    }
    
    public init(view: UIView) {
        
        //
        super.init(frame: CGRect.zero)
        self.showBottom = false
        
        let w = CommonDefine.kScreenWidth
        
        //
        let adjustWidth : CGFloat = w - TuJiaAutoLayoutPopupView.contentFixedWidth
        contentView = UIView(frame: CGRect(x: adjustWidth/2, y: CommonDefine.kScreenFullHeight, width:TuJiaAutoLayoutPopupView.contentFixedWidth, height: view.h))
        contentView!.backgroundColor = UIColor.white
        contentView!.layer.cornerRadius = 10.0
        contentView!.clipsToBounds = true
        contentView!.autoresizesSubviews = true
        //        contentView!.setTranslatesAutoresizingMaskIntoConstraints(true)
        
        contentView!.addSubview(view)
        self.addSubview(contentView!)
        
        //
        self.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
        self.frame = CGRect(x: 0.0, y: 0.0, width: w, height: contentView!.frame.origin.y)
    }
    
    public convenience init(controller: UIViewController, leftItem: String, rightItem: String? = nil, rightAction:(()->Void)? = nil) {
        self.init(view: controller.view, leftItem: leftItem, rightItem: rightItem, rightAction: rightAction)
        self.controller = controller
    }
    
    public convenience init(controller: UIViewController) {
        self.init(view: controller.view)
        self.controller = controller
    }
    
    //
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    //MARK: - Private Function
    @objc public func confirm() -> Void {
        self.hide()
        callBackT?()
    }
    
    @objc public func cancel() {
        self.hide()
        cancelAction?()
    }
    
    override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if(!isAnimation) {
            let touchView = self.hitTest(((touches as NSSet).anyObject()! as AnyObject).location(in: self), with: event)
            if(touchView == self) {
                self.cancel()
            } 
        }
    }
    
    //MARK: - Public Function
    //Resize
    public func resizeHeight(_ height: CGFloat, subview: UIView, animate: Bool = true, force : Bool = false) -> Void {
        if(subview.frame.size.height == height && !force) {
            return
        }
        let action = {
            //
            var frame1: CGRect = subview.frame
            frame1.size.height = height
            subview.frame = frame1
            
            //
            var frame: CGRect = self.contentView!.frame
            frame.size.height = height + (self.showBottom ? self.bottomHeight : 0)
            frame.origin.y = (self.frame.size.height - frame.size.height)/2.0
            self.contentView!.frame = frame
        }
        if !animate {
            action()
            return
        }
        isAnimation = false
        UIView.animate(withDuration: 0.4, animations: { () -> Void in
            action()
        }, completion: { (done) -> Void in
            self.isAnimation = true
        }) 
    }
    
    //show
    open func show() -> Void {
        
        isAnimation = true
//        let win = UIApplication.sharedApplication().windows.last as UIWindow
//        win.addSubview(self)
        let win = UIApplication.shared.keyWindow
        win?.addSubview(self)
        if let ctrl = self.controller {
            if let currentCtrl = win?.getViewController() {
                currentCtrl.addChild(ctrl)
                ctrl.didMove(toParent: currentCtrl)
            }
        }
        
        
        UIView.animate(withDuration: 0.8, delay: 0.1, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: UIView.AnimationOptions.curveEaseIn, animations: { () -> Void in
            var frame: CGRect = self.contentView!.frame
            frame.origin.y = (CommonDefine.kScreenWorkHeight-frame.size.height)/2.0
            self.contentView!.frame = frame
        }) { (done) -> Void in
            self.isAnimation = false
        }
    }
    
    
    //hide
    open func hide() -> Void {
        
        self.endEditing(true)
        
        UIView.animate(withDuration: 0.4, animations: { () -> Void in
            var frame: CGRect = self.contentView!.frame
            frame.origin.y = CommonDefine.kScreenFullHeight
            self.contentView!.frame = frame
        })
        
        UIView.animate(withDuration: 0.3, delay: 0.4, options: UIView.AnimationOptions(), animations: { () -> Void in
            self.alpha = 0.0
        }) { (done) -> Void in
            self.removeFromSuperview()
            self.controller?.removeFromParent()
            self.alpha = 1.0;
        }
    }
    
    //单独添加关于键盘的
    public class func showOfKeyboardAlert(_ title: String, keyoardHeight: CGFloat = 0, cancelItem: String, otherItem: String? = nil, callback:(()->Void)? = nil) -> PMSPopupView {
        let label = UILabel(frame: CGRect(x: -0.5, y: -0.5, width: CommonDefine.kScreenWorkHeight-19.0, height: 112.0))
        label.text = title as String
        label.numberOfLines = 0
        label.textAlignment = .center
        label.layer.borderColor = CommonColors.kBorderColor.cgColor
        label.setBorder(color: CommonColors.kBorderColor)
        
        let popview: PMSPopupView = PMSPopupView(view: label, leftItem: cancelItem, rightItem: otherItem, rightAction: callback)
        popview.showOfKeyboard(keyoardHeight)
        return popview
    }
    
    public func showOfKeyboard(_ keyHeight: CGFloat) -> Void {
        
        isAnimation = true
        UIApplication.shared.keyWindow?.addSubview(self)
        
        UIView.animate(withDuration: 0.8, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: UIView.AnimationOptions.curveEaseIn, animations: { () -> Void in
            var frame: CGRect = self.contentView!.frame
            
            frame.origin.y = (CommonDefine.kScreenWorkHeight-frame.size.height)/2.0
            if keyHeight > 0 {
                frame.origin.y = CommonDefine.kScreenWorkHeight-frame.size.height - keyHeight
            }
            self.contentView!.frame = frame
            }) { (done) -> Void in
                self.isAnimation = false
        }
    }

}

// 只是为了定制
public class PMSPopupViewManualHide : PMSPopupView {
    fileprivate var rightActionShouldHide : (()-> Bool)?
    
    init(view: UIView, leftItem: String, rightItem: String, rightActionShouldHide: (() -> Bool)?) {
        super.init(view: view, leftItem: leftItem, rightItem: rightItem, rightAction: nil)
        self.rightActionShouldHide = rightActionShouldHide
    }

    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override public func confirm() {
        if self.rightActionShouldHide?() == false {
            // donoting
        } else {
            self.hide()
        }
    }
}
